<template>
  <div class="map-view">
    <div class="map-header">
      <h2>3D钢厂模型</h2>
      <div class="map-tools">
        <el-button-group>
          <el-button @click="zoomIn">放大</el-button>
          <el-button @click="zoomOut">缩小</el-button>
          <el-button @click="resetView">重置</el-button>
          <el-button @click="loadModel" :loading="loading" type="primary">{{ modelLoaded ? '重新加载' : '加载Ion模型' }}</el-button>
          <el-button @click="validateToken" type="warning">验证Token</el-button>
        </el-button-group>
        <div class="model-tips">
          <el-text size="small" type="info">💡 现在优先使用Cesium Ion Asset ID加载，解决纹理格式问题</el-text>
        </div>
      </div>
    </div>
    
    <div class="map-container">
      <div ref="mapContainer" class="cesium-container"></div>
      
      <!-- 模型控制面板 -->
      <div class="map-controls">
        <el-card>
          <h4>3D模型信息</h4>
          <div class="model-info">
            <div class="info-item">
              <span class="label">模型状态:</span>
              <el-tag :type="modelLoaded ? 'success' : 'info'" size="small">
                {{ modelLoaded ? '已加载' : '未加载' }}
              </el-tag>
            </div>
            <div class="info-item">
              <span class="label">加载进度:</span>
              <el-progress :percentage="loadProgress" :status="loadProgress === 100 ? 'success' : undefined" />
            </div>
            <div class="info-item">
              <span class="label">模型数据源:</span>
              <el-tag size="small" type="success">Cesium Ion (Asset ID: 3689434)</el-tag>
            </div>
            <div class="info-item">
              <span class="label">纹理状态:</span>
              <el-tag size="small" type="success">已预处理兼容</el-tag>
            </div>
            <div class="info-item">
              <span class="label">特别说明:</span>
              <el-text type="success" size="small">使用Ion平台解决了纹理格式问题</el-text>
            </div>
          </div>
          
          <el-divider />
          
          <h4>视角控制</h4>
          <div class="view-controls">
            <el-button size="small" @click="setTopView">俯视图</el-button>
            <el-button size="small" @click="setFrontView">正视图</el-button>
            <el-button size="small" @click="setSideView">侧视图</el-button>
            <el-button size="small" @click="setIsometricView">等轴视图</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { ElButton, ElButtonGroup, ElCard, ElDivider, ElProgress, ElTag, ElText } from 'element-plus'
import { cesiumConfig } from '@/config/cesium'

// 响应式数据
const mapContainer = ref<HTMLElement>()
const viewer = ref<any>(null) // vue-cesium的viewer类型
const tileset = ref<any>(null) // vue-cesium的tileset类型
const loading = ref(false)
const modelLoaded = ref(false)
const loadProgress = ref(0)

// 方法
const initViewer = async () => {
  if (!mapContainer.value) return
  
  try {
    // 注意：这个文件需要cesium包，但我们已经移除了
    // 建议使用vue-cesium组件或者重新安装cesium包
    console.warn('此文件需要cesium包，请重新安装或使用vue-cesium组件')
    return
    
    // 设置背景颜色
    viewer.value.scene.backgroundColor = Cesium.Color.fromCssColorString('#2c3e50')
    
    // 禁用默认的地球表面
    viewer.value.scene.globe.show = false
    if (viewer.value.scene.skyBox) {
      viewer.value.scene.skyBox.show = false
    }
    if (viewer.value.scene.sun) {
      viewer.value.scene.sun.show = false
    }
    if (viewer.value.scene.moon) {
      viewer.value.scene.moon.show = false
    }
    
    console.log('Cesium Viewer 初始化成功')
  } catch (error) {
    console.error('Cesium Viewer 初始化失败:', error)
  }
}

const loadModel = async () => {
  if (!viewer.value) {
    console.error('Viewer 未初始化')
    return
  }
  
  loading.value = true
  loadProgress.value = 0
  
  try {
    // 如果已经加载了模型，先移除
    if (tileset.value) {
      viewer.value.scene.primitives.remove(tileset.value)
      tileset.value = null
    }
    
    // 清除现有实体
    viewer.value.entities.removeAll()
    
    console.log('🚀 开始Ion模型加载流程...')
    console.log('📋 Token状态:', Cesium.Ion.defaultAccessToken ? '已配置' : '❌ 未配置')
    console.log('🌐 Asset ID: 3689434')
    
    // 🔧 增强的Ion加载策略
    await loadIonModelWithRetry()
    
  } catch (error: any) {
    console.error('❌ 所有加载方案都失败了:', error)
    
    // 显示具体错误信息给用户
    const errorMessage = error?.message || '未知错误'
    alert(`🚫 模型加载完全失败\n\n错误详情: ${errorMessage}\n\n建议检查:\n• 网络连接是否正常\n• Cesium Token是否有效\n• 联系模型提供方确认Asset状态`)
    
    // 最终备用方案：创建简单模型
    createSimpleModel()
  } finally {
    loading.value = false
  }
}

// 🔄 带重试机制的Ion模型加载
const loadIonModelWithRetry = async (maxRetries = 3) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`🔄 Ion加载尝试 ${attempt}/${maxRetries}...`)
      
      // 验证Token有效性
      if (!Cesium.Ion.defaultAccessToken) {
        throw new Error('Cesium Ion Token未配置')
      }
      
      // 创建加载选项
      const loadOptions = {
        // 启用错误容忍模式
        skipLevelOfDetail: true,
        maximumScreenSpaceError: 64, // 降低质量要求
        dynamicScreenSpaceError: true,
        
        // 内存优化
        maximumMemoryUsage: 256,
        
        // 网络优化
        preloadWhenHidden: false,
        preloadFlightDestinations: false,
        
        // 错误处理
        enablePick: false,
        enableCollision: false
      }
      
      console.log('⚙️ 使用优化的加载参数:', loadOptions)
      
      // 使用带选项的fromIonAssetId方法
      tileset.value = await Cesium.Cesium3DTileset.fromIonAssetId(3689434, loadOptions)
      
      console.log('✅ Ion模型创建成功，正在添加到场景...')
      viewer.value!.scene.primitives.add(tileset.value)
      
      // 设置错误监听器
      setupTilesetErrorHandling(tileset.value)
      
      // 应用样式
      await applyModelStyling(tileset.value)
      
      // 设置视角
      await setupModelView(tileset.value)
      
      modelLoaded.value = true
      loadProgress.value = 100
      
      console.log('🎉 Ion模型加载完全成功！')
      return // 成功后退出重试循环
      
    } catch (error: any) {
      console.warn(`⚠️ Ion加载尝试 ${attempt} 失败:`, error.message)
      
      if (attempt === maxRetries) {
        // 最后一次尝试失败，抛出错误
        throw new Error(`Ion加载失败 (${maxRetries}次尝试): ${error.message}`)
      }
      
      // 等待一段时间后重试
      console.log(`⏳ 等待 ${attempt * 2} 秒后重试...`)
      await new Promise(resolve => setTimeout(resolve, attempt * 2000))
    }
  }
}

// 🛡️ 设置模型错误处理
const setupTilesetErrorHandling = (tileset: Cesium.Cesium3DTileset) => {
  // 监听瓦片加载失败事件
  // @ts-ignore - Cesium类型定义可能不完整
  if (tileset.tileLoadFailure) {
    (tileset as any).tileLoadFailure.addEventListener((event: any) => {
      console.warn('🔧 某个瓦片加载失败，但继续加载其他部分:', {
        url: event.url,
        message: event.message
      })
      
      // 不中断整体加载过程
      loadProgress.value = Math.min(loadProgress.value + 5, 95)
    })
  }
  
  // 监听所有瓦片加载完成
  // @ts-ignore - Cesium类型定义可能不完整
  if (tileset.allTilesLoaded) {
    (tileset as any).allTilesLoaded.addEventListener(() => {
      console.log('🏁 所有可用瓦片已加载完成')
      loadProgress.value = 100
    })
  }
}

// 🎨 应用模型样式
const applyModelStyling = async (tileset: Cesium.Cesium3DTileset) => {
  try {
    // 优先使用Ion默认样式
    const extras = tileset.asset?.extras
    if (extras?.ion?.defaultStyle) {
      tileset.style = new Cesium.Cesium3DTileStyle(extras.ion.defaultStyle)
      console.log('🎨 已应用Ion默认样式')
    } else {
      // 备用样式：使用建筑物风格
      tileset.style = new Cesium.Cesium3DTileStyle({
        color: {
          evaluateColor: function(feature: any, result: any) {
            // 根据高度给不同颜色
            const height = feature.getProperty('height') || 10
            if (height > 50) {
              return Cesium.Color.STEELBLUE.clone(result)
            } else if (height > 20) {
              return Cesium.Color.LIGHTSTEELBLUE.clone(result)
            } else {
              return Cesium.Color.LIGHTGRAY.clone(result)
            }
          }
        },
        show: true
      })
      console.log('🎨 已应用备用建筑样式')
    }
  } catch (styleError) {
    console.warn('⚠️ 样式应用失败，使用默认样式:', styleError)
  }
}

// 📐 设置模型视角
const setupModelView = async (tileset: Cesium.Cesium3DTileset) => {
  try {
    console.log('📐 正在调整相机视角...')
    
    // 等待模型准备就绪 (使用类型断言)
    // @ts-ignore - Cesium类型定义可能不完整
    if ((tileset as any).readyPromise) {
      await (tileset as any).readyPromise
    }
    
    // 缩放到模型
    await viewer.value!.zoomTo(tileset, new Cesium.HeadingPitchRange(
      0,        // heading: 北向
      -0.5,     // pitch: 俯视角度
      tileset.boundingSphere.radius * 2.5  // range: 适当距离
    ))
    
    console.log('📐 相机视角设置完成')
    
  } catch (viewError) {
    console.warn('⚠️ 视角设置失败，使用默认位置:', viewError)
    
    // 备用视角设置
    viewer.value!.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(118.2, 39.6, 2000),
      orientation: {
        heading: Cesium.Math.toRadians(0),
        pitch: Cesium.Math.toRadians(-45),
        roll: 0.0
      }
    })
  }
}

// 本地文件备用加载方法
const loadLocalFilesFallback = async () => {
  console.log('📂 开始本地文件备用加载...')
  
  const tilesetUrl = '/models/ZongHengHP_3dtiles/tileset.json'
  
  // 使用更宽松的参数，专门处理纹理问题
  const tilesetOptions = {
    // 降低精度要求，减少纹理相关错误
    maximumScreenSpaceError: 64,
    skipLevelOfDetail: true,
    baseScreenSpaceError: 4096,
    skipScreenSpaceErrorFactor: 64,
    skipLevels: 3,
    immediatelyLoadDesiredLevelOfDetail: false,
    loadSiblings: false,
    cullWithChildrenBounds: true,
    
    // 禁用可能导致纹理问题的功能
    enablePick: false,
    enableCollision: false,
    shadows: Cesium.ShadowMode.DISABLED,
    
    // 内存限制，强制简化
    maximumMemoryUsage: 128,
    
    // 预加载设置
    preloadWhenHidden: false,
    preloadFlightDestinations: false,
    
    // 调试模式
    debugShowBoundingVolume: false,
    debugShowContentBoundingVolume: false
  }
  
  console.log('使用本地文件加载参数:', tilesetOptions)
  
  tileset.value = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, tilesetOptions)
  
  console.log('本地文件加载成功，正在添加到场景...')
  viewer.value!.scene.primitives.add(tileset.value)
  
  // 使用简单的纯色样式来避免纹理问题
  tileset.value.style = new Cesium.Cesium3DTileStyle({
    color: 'color("lightsteelblue")',
    show: true
  })
  
  console.log('已应用纯色样式')
  
  modelLoaded.value = true
  loadProgress.value = 100
  
  console.log('本地 3D Tiles 模型初始加载成功')
  
  // 飞行到模型位置
  setTimeout(() => {
    if (viewer.value && tileset.value) {
      console.log('正在飞行到模型位置...')
      try {
        viewer.value.zoomTo(tileset.value, new Cesium.HeadingPitchRange(0, -0.5, 0))
        console.log('飞行完成')
      } catch (zoomError) {
        console.warn('飞行到模型失败:', zoomError)
        viewer.value!.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(118.2, 39.6, 2000)
        })
      }
    }
  }, 2000)
}

// 直接使用Ion Asset ID加载模型
const loadIonModel = async () => {
  if (!viewer.value) {
    console.error('Viewer 未初始化')
    return
  }
  
  loading.value = true
  loadProgress.value = 0
  
  try {
    // 如果已经加载了模型，先移除
    if (tileset.value) {
      viewer.value.scene.primitives.remove(tileset.value)
      tileset.value = null
    }
    
    // 清除现有实体
    viewer.value.entities.removeAll()
    
    console.log('直接从Cesium Ion加载模型 (Asset ID: 3689434)...')
    console.log('Token:', Cesium.Ion.defaultAccessToken ? '已配置' : '未配置')
    
    // 使用Cesium提供的标准代码
    tileset.value = await Cesium.Cesium3DTileset.fromIonAssetId(3689434)
    viewer.value.scene.primitives.add(tileset.value)
    await viewer.value.zoomTo(tileset.value)
    
    // 应用Ion平台的默认样式方法
    const extras = tileset.value.asset.extras
    if (
      Cesium.defined(extras) &&
      Cesium.defined(extras.ion) &&
      Cesium.defined(extras.ion.defaultStyle)
    ) {
      tileset.value.style = new Cesium.Cesium3DTileStyle(extras.ion.defaultStyle)
      console.log('已应用Ion默认样式')
    }
    
    modelLoaded.value = true
    loadProgress.value = 100
    
    console.log('Ion 3D Tiles 模型加载成功！')
    
  } catch (error: any) {
    console.error('Ion模型加载失败:', error)
    alert(`Ion模型加载失败: ${error?.message || '未知错误'}\n\n请检查:  \n1. Cesium Token是否正确\n2. 网络连接是否正常\n3. Asset ID是否有效`)
  } finally {
    loading.value = false
  }
}

// 🔐 验证Cesium Ion Token
const validateToken = async () => {
  loading.value = true
  console.log('🔐 开始验证Cesium Ion Token...')
  
  try {
    const token = Cesium.Ion.defaultAccessToken
    if (!token) {
      throw new Error('Token未配置')
    }
    
    console.log('📋 Token略缩:', `${token.substring(0, 20)}...${token.substring(token.length - 10)}`)
    
    // 使用Cesium Ion API验证Token
    const response = await fetch('https://api.cesium.com/v1/me', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.ok) {
      const userData = await response.json()
      console.log('✅ Token验证成功！用户信息:', {
        id: userData.id,
        username: userData.username,
        email: userData.email
      })
      
      // 检查Asset权限
      await checkAssetAccess(token)
      
      alert('✅ Token验证成功！\n\n用户ID: ' + userData.id + '\n用户名: ' + userData.username + '\n现在可以尝试加载模型了。')
      
    } else {
      const errorData = await response.text()
      console.error('❌ Token验证失败:', response.status, errorData)
      
      if (response.status === 401) {
        alert('❌ Token验证失败！\n\n错误原因: Token无效或过期\n\n请检查:\n• Token是否正确\n• Token是否过期\n• 网络连接是否正常')
      } else {
        alert(`❌ Token验证失败！\n\nHTTP ${response.status}\n\n请检查网络连接和服务状态。`)
      }
    }
    
  } catch (error: any) {
    console.error('❌ Token验证遇到错误:', error)
    alert(`❌ Token验证失败！\n\n错误信息: ${error?.message || '未知错误'}\n\n可能原因:\n• 网络连接问题\n• CORS限制\n• 防火墙阻拦`)
  } finally {
    loading.value = false
  }
}

// 📋 检查特定Asset访问权限
const checkAssetAccess = async (token: string) => {
  try {
    console.log('📋 检查Asset ID 3689434的访问权限...')
    
    const assetResponse = await fetch('https://api.cesium.com/v1/assets/3689434', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (assetResponse.ok) {
      const assetData = await assetResponse.json()
      console.log('✅ Asset访问权限正常！Asset信息:', {
        id: assetData.id,
        name: assetData.name,
        description: assetData.description,
        type: assetData.type,
        status: assetData.status
      })
      
      if (assetData.status !== 'COMPLETE') {
        console.warn('⚠️ Asset状态异常:', assetData.status)
        alert(`⚠️ 模型状态异常！\n\nAsset状态: ${assetData.status}\n\n如果状态不是COMPLETE，可能导致加载失败。请等待处理完成或联系管理员。`)
      }
      
    } else {
      console.error('❌ Asset访问被拒绝:', assetResponse.status)
      
      if (assetResponse.status === 404) {
        alert('❌ Asset访问失败！\n\nAsset ID 3689434 不存在或无访问权限。\n\n请检查:\n• Asset ID是否正确\n• 是否有访问权限\n• Asset是否已删除')
      } else if (assetResponse.status === 403) {
        alert('❌ Asset访问被拒绝！\n\n您没有访问该Asset的权限。\n\n请联系模型所有者或管理员授予访问权限。')
      }
    }
    
  } catch (assetError: any) {
    console.error('❌ Asset检查失败:', assetError)
    console.log('⚠️ 无法检查Asset访问权限，但这不影响Token的有效性')
  }
}

// 备用加载方法，尝试加载单个子模型
const loadFallbackModel = async () => {
  try {
    console.log('尝试加载备用模型...')
    
    // 尝试加载 Alpha 子模型（最有可能成功的）
    const fallbackModules = [
      '/models/ZongHengHP_3dtiles/Alpha/tileset.json',
      '/models/ZongHengHP_3dtiles/JianZhu/tileset.json',
      '/models/ZongHengHP_3dtiles/JianZhu2/tileset.json'
    ]
    
    for (const fallbackUrl of fallbackModules) {
      try {
        console.log('尝试加载子模型:', fallbackUrl)
        
        // 使用正常的加载参数，但更保守
        const simpleTilesetOptions = {
          maximumScreenSpaceError: 32, // 正常精度
          skipLevelOfDetail: true,
          baseScreenSpaceError: 2048,
          skipScreenSpaceErrorFactor: 32,
          skipLevels: 2, // 跳过两个级别
          immediatelyLoadDesiredLevelOfDetail: false,
          loadSiblings: false,
          cullWithChildrenBounds: true,
          
          // 基本功能
          enablePick: true,
          enableCollision: false,
          shadows: Cesium.ShadowMode.ENABLED,
          
          // 内存管理
          maximumMemoryUsage: 256,
          
          // 动态优化
          dynamicScreenSpaceError: true,
          
          // 预加载设置
          preloadWhenHidden: false,
          preloadFlightDestinations: true
        }
        
        tileset.value = await Cesium.Cesium3DTileset.fromUrl(fallbackUrl, simpleTilesetOptions)
        
        console.log('子模型加载成功，正在添加到场景...')
        
        viewer.value!.scene.primitives.add(tileset.value)
        
        // 设置简单样式
        tileset.value.style = new Cesium.Cesium3DTileStyle({
          color: 'color("lightsteelblue")', // 钉灰色
          show: true
        })
        
        modelLoaded.value = true
        loadProgress.value = 100
        
        console.log('子模型设置完成')
        
        // 飞行到模型
        setTimeout(() => {
          if (viewer.value && tileset.value) {
            try {
              viewer.value.zoomTo(tileset.value, new Cesium.HeadingPitchRange(0, -0.5, 0))
              console.log('子模型飞行完成')
            } catch (zoomError) {
              console.warn('子模型飞行失败:', zoomError)
              viewer.value!.camera.setView({
                destination: Cesium.Cartesian3.fromDegrees(118.2, 39.6, 1500)
              })
            }
          }
        }, 1000)
        
        console.log('子模型加载完成')
        return // 成功加载一个就退出
        
      } catch (moduleError) {
        console.warn(`子模型 ${fallbackUrl} 加载失败:`, moduleError)
        continue // 尝试下一个
      }
    }
    
    // 所有子模型都失败了
    throw new Error('所有子模型都加载失败')
    
  } catch (fallbackError) {
    console.error('子模型也加载失败:', fallbackError)
    console.log('尝试创建简单模型作为最后备用方案...')
    
    // 最后的备用方案：创建简单模型
    createSimpleModel()
  }
}

// 创建简单的测试模型
const createSimpleModel = () => {
  if (!viewer.value) return
  
  console.log('创建简单测试模型...')
  
  // 清除现有实体
  viewer.value.entities.removeAll()
  if (tileset.value) {
    viewer.value.scene.primitives.remove(tileset.value)
    tileset.value = null
  }
  
  // 创建多个简单的建筑模型
  const buildings = [
    // 主厂房
    {
      position: Cesium.Cartesian3.fromDegrees(118.175393, 39.635113, 50),
      dimensions: new Cesium.Cartesian3(200, 100, 30),
      color: Cesium.Color.LIGHTSTEELBLUE,
      name: '主厂房'
    },
    // 办公楼
    {
      position: Cesium.Cartesian3.fromDegrees(118.176000, 39.635500, 40),
      dimensions: new Cesium.Cartesian3(80, 60, 50),
      color: Cesium.Color.LIGHTBLUE,
      name: '办公楼'
    },
    // 仓库
    {
      position: Cesium.Cartesian3.fromDegrees(118.174800, 39.634800, 25),
      dimensions: new Cesium.Cartesian3(150, 80, 20),
      color: Cesium.Color.LIGHTGRAY,
      name: '仓库'
    },
    // 烟囱
    {
      position: Cesium.Cartesian3.fromDegrees(118.175800, 39.635800, 75),
      dimensions: new Cesium.Cartesian3(10, 10, 100),
      color: Cesium.Color.DARKGRAY,
      name: '烟囱'
    }
  ]
  
  buildings.forEach(building => {
    viewer.value!.entities.add({
      name: building.name,
      position: building.position,
      box: {
        dimensions: building.dimensions,
        material: building.color,
        outline: true,
        outlineColor: Cesium.Color.BLACK
      },
      label: {
        text: building.name,
        font: '14pt sans-serif',
        pixelOffset: new Cesium.Cartesian2(0, -50),
        fillColor: Cesium.Color.YELLOW,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE
      }
    })
  })
  
  // 设置相机视角
  viewer.value.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(118.175393, 39.635113, 500),
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-45),
      roll: 0.0
    }
  })
  
  modelLoaded.value = true
  loadProgress.value = 100
  
  console.log('简单测试模型创建成功')
}

// 仅加载几何体，不加载纹理
const loadGeometryOnly = async () => {
  if (!viewer.value) return
  
  loading.value = true
  console.log('尝试仅加载几何体，忽略纹理...')
  
  try {
    // 清除现有内容
    viewer.value.entities.removeAll()
    if (tileset.value) {
      viewer.value.scene.primitives.remove(tileset.value)
      tileset.value = null
    }
    
    // 使用极端的参数，只加载最基本的几何体
    const geometryOnlyOptions = {
      maximumScreenSpaceError: 2048, // 非常大的值
      skipLevelOfDetail: true,
      baseScreenSpaceError: 32768,
      skipScreenSpaceErrorFactor: 512,
      skipLevels: 15, // 跳过几乎所有级别
      immediatelyLoadDesiredLevelOfDetail: false,
      loadSiblings: false,
      cullWithChildrenBounds: true,
      enablePick: false,
      enableCollision: false,
      shadows: Cesium.ShadowMode.DISABLED,
      maximumMemoryUsage: 8, // 最小内存使用
      preloadWhenHidden: false,
      preloadFlightDestinations: false,
      // 关键：强制禁用材质和纹理加载
      enableModelExperimental: false,
      enableDebugWireframe: true // 使用线框模式
    }
    
    const tilesetUrl = '/models/ZongHengHP_3dtiles/tileset.json'
    
    tileset.value = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, geometryOnlyOptions)
    
    viewer.value.scene.primitives.add(tileset.value)
    
    // 设置纯线框样式
    tileset.value.style = new Cesium.Cesium3DTileStyle({
      color: 'color("white")',
      show: true,
      // 强制使用线框模式
      outlineColor: 'color("black")',
      outlineWidth: 1
    })
    
    // 强制启用线框模式
    if (tileset.value.debugWireframe !== undefined) {
      tileset.value.debugWireframe = true
    }
    
    modelLoaded.value = true
    loadProgress.value = 100
    
    setTimeout(() => {
      if (viewer.value && tileset.value) {
        try {
          viewer.value.zoomTo(tileset.value)
          console.log('几何体模式加载成功')
        } catch (zoomError) {
          console.warn('飞行失败:', zoomError)
          viewer.value!.camera.setView({
            destination: Cesium.Cartesian3.fromDegrees(118.175393, 39.635113, 1000)
          })
        }
      }
    }, 1000)
    
  } catch (error) {
    console.error('几何体模式也加载失败:', error)
    // 最后的备用方案
    createSimpleModel()
  } finally {
    loading.value = false
  }
}

// 系统诊断函数
const diagnoseSystem = async () => {
  console.log('=== 系统诊断开始 ===')
  
  // 检查 Cesium 初始化
  console.log('1. Cesium 版本:', (Cesium as any).VERSION || '未知')
  console.log('2. Cesium Token:', Cesium.Ion.defaultAccessToken ? '已配置' : '未配置')
  
  // 检查 Viewer 状态
  if (viewer.value) {
    console.log('3. Viewer 状态:', '已初始化')
    console.log('   - Scene primitives 数量:', viewer.value.scene.primitives.length)
    console.log('   - Entities 数量:', viewer.value.entities.values.length)
    console.log('   - Camera 位置:', viewer.value.camera.position)
  } else {
    console.log('3. Viewer 状态:', '未初始化')
  }
  
  // 检查模型文件可访问性
  console.log('4. 模型文件检查:')
  const urls = [
    '/models/ZongHengHP_3dtiles/tileset.json',
    '/models/ZongHengHP_3dtiles/JianZhu/tileset.json',
    '/models/ZongHengHP_3dtiles/Alpha/tileset.json'
  ]
  
  for (const url of urls) {
    try {
      const response = await fetch(url)
      if (response.ok) {
        const data = await response.json()
        console.log(`   - ${url}: 可访问 (大小: ${response.headers.get('content-length')} bytes)`)
        console.log(`     子节点数: ${data.root?.children?.length || 0}`)
      } else {
        console.log(`   - ${url}: HTTP ${response.status}`)
      }
    } catch (error: any) {
      console.log(`   - ${url}: 访问失败 - ${error?.message || error}`)
    }
  }
  
  // 检查浏览器支持
  console.log('5. 浏览器支持:')
  // @ts-ignore - Cesium内部属性
  console.log('   - WebGL:', viewer.value?.scene?.context?.webgl2 ? 'WebGL2' : 'WebGL1')
  // @ts-ignore - Cesium内部属性
  console.log('   - 最大纹理尺寸:', viewer.value?.scene?.context?.maximumTextureSize)
  
  // 尝试加载最简单的b3dm文件
  console.log('6. 尝试加载单个b3dm文件:')
  try {
    if (viewer.value) {
      const simpleTileset = await Cesium.Cesium3DTileset.fromUrl('/models/ZongHengHP_3dtiles/JianZhu/NoLod_0.b3dm')
      console.log('   - 单个b3dm文件加载成功')
      viewer.value.scene.primitives.add(simpleTileset)
      setTimeout(() => {
        if (viewer.value && simpleTileset) {
          viewer.value.scene.primitives.remove(simpleTileset)
        }
      }, 2000)
    }
  } catch (b3dmError: any) {
    console.log('   - 单个b3dm文件加载失败:', b3dmError?.message || b3dmError)
  }
  
  console.log('=== 系统诊断完成 ===')
}

const zoomIn = () => {
  if (viewer.value) {
    viewer.value.camera.zoomIn(viewer.value.camera.positionCartographic.height * 0.5)
  }
}

const zoomOut = () => {
  if (viewer.value) {
    viewer.value.camera.zoomOut(viewer.value.camera.positionCartographic.height * 0.5)
  }
}

const resetView = () => {
  if (viewer.value && tileset.value) {
    viewer.value.zoomTo(tileset.value)
  }
}

// 视角控制方法
const setTopView = () => {
  if (viewer.value && tileset.value) {
    const boundingSphere = tileset.value.boundingSphere
    const range = boundingSphere.radius * 2
    
    viewer.value.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        Cesium.Math.toDegrees(boundingSphere.center.x),
        Cesium.Math.toDegrees(boundingSphere.center.y),
        range
      ),
      orientation: {
        heading: 0.0,
        pitch: Cesium.Math.toRadians(-90),
        roll: 0.0
      }
    })
  }
}

const setFrontView = () => {
  if (viewer.value && tileset.value) {
    const boundingSphere = tileset.value.boundingSphere
    const range = boundingSphere.radius * 3
    
    viewer.value.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        Cesium.Math.toDegrees(boundingSphere.center.x),
        Cesium.Math.toDegrees(boundingSphere.center.y) - 0.01,
        boundingSphere.center.z + range * 0.3
      ),
      orientation: {
        heading: 0.0,
        pitch: Cesium.Math.toRadians(-10),
        roll: 0.0
      }
    })
  }
}

const setSideView = () => {
  if (viewer.value && tileset.value) {
    const boundingSphere = tileset.value.boundingSphere
    const range = boundingSphere.radius * 3
    
    viewer.value.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        Cesium.Math.toDegrees(boundingSphere.center.x) + 0.01,
        Cesium.Math.toDegrees(boundingSphere.center.y),
        boundingSphere.center.z + range * 0.3
      ),
      orientation: {
        heading: Cesium.Math.toRadians(-90),
        pitch: Cesium.Math.toRadians(-10),
        roll: 0.0
      }
    })
  }
}

const setIsometricView = () => {
  if (viewer.value && tileset.value) {
    const boundingSphere = tileset.value.boundingSphere
    const range = boundingSphere.radius * 2.5
    
    viewer.value.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(
        Cesium.Math.toDegrees(boundingSphere.center.x) + 0.005,
        Cesium.Math.toDegrees(boundingSphere.center.y) + 0.005,
        boundingSphere.center.z + range
      ),
      orientation: {
        heading: Cesium.Math.toRadians(-45),
        pitch: Cesium.Math.toRadians(-30),
        roll: 0.0
      }
    })
  }
}

// 生命周期
onMounted(async () => {
  await initViewer()
  // 自动加载模型
  setTimeout(() => {
    loadModel()
  }, 1000)
})

onUnmounted(() => {
  if (tileset.value && viewer.value) {
    viewer.value.scene.primitives.remove(tileset.value)
  }
  if (viewer.value) {
    viewer.value.destroy()
    viewer.value = null
  }
})
</script>

<style scoped>
.map-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.map-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.map-header h2 {
  margin: 0;
  color: #303133;
}

.map-container {
  flex: 1;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.cesium-container {
  width: 100%;
  height: 100%;
  background: #000;
}

.map-controls {
  position: absolute;
  top: 16px;
  right: 16px;
  width: 280px;
  max-height: 400px;
  overflow-y: auto;
}

.model-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 70px;
}

.view-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.view-controls .el-button {
  width: 100%;
}

.model-tips {
  margin-top: 8px;
  padding: 8px;
  background: #e8f4fd;
  border-radius: 4px;
  border-left: 3px solid #409eff;
}

@media (max-width: 768px) {
  .map-controls {
    position: static;
    width: 100%;
    margin-top: 16px;
  }
}
</style>